import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:yqys_target/gen/assets.gen.dart';
import 'package:yqys_target/utils/yq_screen_util.dart';
import '../../widgets/form_list_item.dart';
import '../../widgets/xh_auto_height_text_field.dart';
import '../../widgets/yq_upload_images.dart';
import 'package:yqys_target/widgets/yq_range_date_time_picker.dart';
import './launch_charity_controller.dart';

const _kHeaderHeight = 230.0;
const _kAppBarHeight = 56.0;
const _kScrollHeadHeight = 100.0;

class LaunchCharityPage extends StatelessWidget {
  const LaunchCharityPage({super.key});

  @override
  Widget build(BuildContext context) {
    // 初始化控制器
    Get.put(LaunchCharityController());
    return GetBuilder<LaunchCharityController>(
      builder: (controller) {
        final backgroundColor = Color.lerp(
          Colors.transparent,
          Colors.white,
          controller.scrollOpacity,
        );

        final textColor = Color.lerp(
          Colors.white,
          Colors.black,
          controller.scrollOpacity,
        );

        return AnnotatedRegion<SystemUiOverlayStyle>(
          value: SystemUiOverlayStyle(
            statusBarColor: Colors.transparent,
            statusBarIconBrightness: controller.isDark ? Brightness.light : Brightness.dark,
            statusBarBrightness: controller.isDark ? Brightness.light : Brightness.dark,
          ),
          child: Scaffold(
            backgroundColor: Colors.grey[100],
            body: Stack(
              children: [
                // 背景图
                const _HeaderBgImage(),
                // 主滚动内容
                CustomScrollView(
                  controller: controller.scrollController,
                  slivers: [
                    // 透明AppBar
                    _DetailAppBar(
                      textColor: textColor,
                      backgroundColor: backgroundColor,
                    ),
                    const _ScrollHeadPlaceHolder(),
                    // 第一组：基本信息
                    SliverPadding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      sliver: SliverToBoxAdapter(
                        child: _BasicInfoSection(),
                      ),
                    ),
                    const SliverToBoxAdapter(
                      child: SizedBox(height: 16),
                    ),
                    // 第二组：项目信息
                    SliverPadding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      sliver: SliverToBoxAdapter(
                        child: _ProjectInfoSection(),
                      ),
                    ),
                    const SliverToBoxAdapter(
                      child: SizedBox(height: 16),
                    ),
                    // 第三组：封面背景图
                    SliverPadding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      sliver: SliverToBoxAdapter(
                        child: _CoverImageSection(),
                      ),
                    ),
                    const SliverToBoxAdapter(
                      child: SizedBox(height: 16),
                    ),
                    // 第四组：相关图片
                    SliverPadding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      sliver: SliverToBoxAdapter(
                        child: _RelatedImagesSection(),
                      ),
                    ),
                    // 底部空白，为固定按钮留出空间
                    SliverToBoxAdapter(
                      child: SizedBox(
                        height: YQScreenUtil.getBottomSafeHeight() + 80,
                      ),
                    ),
                  ],
                ),
                // 固定在底部的按钮
                _SubmitButton(),
              ],
            ),
          ),
        );
      }
    );
  }
}

class _HeaderBgImage extends StatelessWidget {
  const _HeaderBgImage();

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: SizedBox(
        height: _kHeaderHeight + YQScreenUtil.getStatusBarHeight(),
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            // 背景图
            Positioned.fill(
              child: ClipRRect(
                borderRadius: const BorderRadius.only(
                  bottomLeft: Radius.circular(15),
                  bottomRight: Radius.circular(15),
                ),
                child: Image.asset(
                  Assets.images.organizationHeaderBg.path,
                  fit: BoxFit.cover,
                ),
              ),
            ),
            // 文案
            Positioned(
              top: YQScreenUtil.getStatusBarHeight() + _kAppBarHeight + 16,
              left: 22,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '感召全员参与 转递人间大爱',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 13),
                  SizedBox(
                    height: 23,
                    child: AspectRatio(
                      aspectRatio: 190.0 / 20.0,
                      child: Stack(
                        children: [
                          Positioned.fill(
                            child: Image.asset(
                              Assets.images.headerFocusBg.path,
                              fit: BoxFit.fill,
                            ),
                          ),
                          const Positioned.fill(
                            child: Center(
                              child: Text(
                                '为您的爱心益事保驾护航',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _DetailAppBar extends StatelessWidget {
  const _DetailAppBar({
    required this.textColor,
    required this.backgroundColor,
  });

  final Color? textColor;
  final Color? backgroundColor;

  @override
  Widget build(BuildContext context) {
    return SliverAppBar(
      pinned: true,
      elevation: 0,
      title: Text(
        "发起益事",
        style: TextStyle(color: textColor),
      ),
      backgroundColor: backgroundColor,
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios, color: textColor),
        onPressed: () => Navigator.of(context).pop(),
      ),
    );
  }
}

class _ScrollHeadPlaceHolder extends StatelessWidget {
  const _ScrollHeadPlaceHolder();

  @override
  Widget build(BuildContext context) {
    return const SliverToBoxAdapter(
      child: SizedBox(height: _kScrollHeadHeight),
    );
  }
}

class _BasicInfoSection extends StatefulWidget {
  @override
  State<_BasicInfoSection> createState() => _BasicInfoSectionState();
}

class _BasicInfoSectionState extends State<_BasicInfoSection> {
  final controller = Get.find<LaunchCharityController>();
  String _placeholder = "请选择起始截止时间";

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(10),
      child: Container(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FormListItem(
              title: "益事名称",
              trailing: SizedBox(
                width: 200,
                child: XHAutoHeightTextField(
                  maxLength: 50,
                  width: 200,
                  placeholder: "点击输入益事项目名称",
                  onChanged: controller.updateCharityName,
                ),
              ),
            ),
            FormListItem(
              title: "益事时间",
              trailing: SizedBox(
                width: 200,
                child: GetBuilder<LaunchCharityController>(
                  builder: (controller) => YQRangeDateTimePicker(
                    initialStartDate: controller.startTime,
                    initialEndDate: controller.endTime,
                    onDateTimeRangeSelected: controller.handleDateTimeRangeSelected,
                  ),
                ),
              ),
            ),
            FormListItem(
              title: "筹集目标",
              trailing: SizedBox(
                width: 200,
                child: XHAutoHeightTextField(
                  maxLength: 20,
                  width: 200,
                  placeholder: "请输入金额",
                  numberOnly: true,
                  onChanged: controller.updateFundraisingGoal,
                ),
              ),
            ),
            FormListItem(
              title: "益事目的",
              trailing: SizedBox(
                width: 200,
                child: XHAutoHeightTextField(
                  maxLength: 500,
                  width: 200,
                  placeholder: "请输入益事目的",
                  onChanged: controller.updateCharityPurpose,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _ProjectInfoSection extends StatelessWidget {
  const _ProjectInfoSection();

  @override
  Widget build(BuildContext context) {
    final controller = Get.find<LaunchCharityController>();
    
    return ClipRRect(
      borderRadius: BorderRadius.circular(10),
      child: Container(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            FormListItem(
              title: "发起机构",
              trailing: SizedBox(
                width: 200,
                child: XHAutoHeightTextField(
                  maxLength: 100,
                  width: 200,
                  placeholder: "请输入发起机构",
                  onChanged: controller.updateOrganizationName,
                ),
              ),
            ),
            FormListItem(
              title: "服务对象描述",
              trailing: SizedBox(
                width: 200,
                child: XHAutoHeightTextField(
                  maxLength: 500,
                  width: 200,
                  placeholder: "请输入服务对象描述",
                  onChanged: controller.updateServiceDescription,
                ),
              ),
            ),
            FormListItem(
              title: "益事流程",
              trailing: SizedBox(
                width: 200,
                child: XHAutoHeightTextField(
                  maxLength: 500,
                  width: 200,
                  placeholder: "请输入益事流程",
                  onChanged: controller.updateCharityProcess,
                ),
              ),
            ),
            FormListItem(
              title: "需求及用途",
              trailing: SizedBox(
                width: 200,
                child: XHAutoHeightTextField(
                  maxLength: 500,
                  width: 200,
                  placeholder: "请输入需求及用途",
                  onChanged: controller.updateNeedsAndUses,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _CoverImageSection extends StatelessWidget {
  const _CoverImageSection();

  @override
  Widget build(BuildContext context) {
    final controller = Get.find<LaunchCharityController>();
    
    return ClipRRect(
      borderRadius: BorderRadius.circular(10),
      child: Container(
        color: Colors.white,
        child: GetBuilder<LaunchCharityController>(
          builder: (controller) => YQUploadImages(
            images: controller.coverImages,
            onDelete: controller.handleCoverImageDelete,
            onImagePicked: controller.handleCoverImagePicked,
            maxCount: 1,
            title: '封面背景图',
          ),
        ),
      ),
    );
  }
}

class _RelatedImagesSection extends StatelessWidget {
  const _RelatedImagesSection();

  @override
  Widget build(BuildContext context) {
    final controller = Get.find<LaunchCharityController>();
    
    return ClipRRect(
      borderRadius: BorderRadius.circular(10),
      child: Container(
        color: Colors.white,
        child: GetBuilder<LaunchCharityController>(
          builder: (controller) => YQUploadImages(
            images: controller.relatedImages,
            onDelete: controller.handleRelatedImageDelete,
            onImagePicked: controller.handleRelatedImagePicked,
            maxCount: 9,
            title: '相关图片',
          ),
        ),
      ),
    );
  }
}

class _SubmitButton extends StatelessWidget {
  const _SubmitButton();

  @override
  Widget build(BuildContext context) {
    final controller = Get.find<LaunchCharityController>();
    
    return Positioned(
      left: 0,
      right: 0,
      bottom: 0,
      child: Container(
        padding: EdgeInsets.only(
          left: 16,
          right: 16,
          bottom: YQScreenUtil.getBottomSafeHeight(),
          top: 0,
        ),
        child: ElevatedButton(
          onPressed: controller.submitForm,
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.green,
            fixedSize: const Size(double.infinity, 48),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(24),
            ),
          ),
          child: const Text(
            '提交',
            style: TextStyle(
              fontSize: 20,
              color: Colors.white,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }
}